#!/usr/bin/env python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import asyncio
import contextlib
from .util import SysInfo
from ._game import GameBase
from ._runner import RunnerBase, RunnerContext


class RunGame:

    def __init__(self, sys_info, game_id, game_obj, runner_obj):
        self._gameId = game_id

        assert isinstance(sys_info, SysInfo)
        self._sysInfo = sys_info

        assert isinstance(game_obj, GameBase)
        self._gameObj = game_obj

        assert isinstance(runner_obj, RunnerBase)
        self._runnerObj = runner_obj
        self._runnerObj._initialize(sys_info, game_id, game_obj)

    def prepare(self, edit_or_run):
        self._context = RunnerContext(edit_or_run)

        self._runnerObj._prepare(self._context)
        try:
            self._gameObj._batchCall("_assertContext", self._context)
            hint = self._gameObj._prepare(self._context)
            try:
                self._gameObj._batchCall("_assertHint", hint)
                self._runnerObj._processGameHint(hint)
            except BaseException:
                self._gameObj._cleanup(on_error=True)
                raise
        except BaseException:
            self._runnerObj._cleanup(on_error=True)
            del self._context
            raise

    def run(self, item):
        assert not self._context.edit_or_run
        asyncio.run(self._runnerObj._run(item))

    def cleanup(self, on_error=False):
        self._gameObj._cleanup(on_error)
        self._runnerObj._cleanup(on_error)
        del self._context

    @contextlib.contextmanager
    def context(self, edit_or_run):
        self.prepare(edit_or_run)
        try:
            yield self
        except BaseException:
            self.cleanup(on_error=True)
            raise
        self.cleanup()
